<?php

namespace common\jobs\handle;

use Yii;
use yii\db\Exception;
use common\models\user\UserBranch;
use common\models\member\Member;
use common\models\spread\SpreadAttract;
use common\models\shop\ShopCoupon;
use common\models\user\UserCoupon;
use common\models\member\MemberBranchLog;

/**
 * 会员账户开通任务处理
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class JoinBranchHandle extends \common\jobs\base\BaseJobHandleModel {

    /**
     * @var string 用户手机号
     */
    public $mobile;

    /**
     * @var integer 用户ID
     */
    public $user_id;

    /**
     * @var SpreadAttract|null 推广模型
     */
    private $_model = null;

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['user_id'], 'required'],
            [['user_id'], 'integer'],
            [['mobile'], 'string'],
            [['user_id'], 'validateUser'],
            [['mobile'], 'validateAttract'],
        ];
    }

    /**
     * 校验订单信息
     * @param string $attribute the attribute currently being validated
     */
    public function validateUser($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $uid = $this->$attribute;
        $query = SpreadAttract::find()->alias('t')->active();
        $query->joinWith('connect connect');
        $query->andWhere(['connect.user_id' => $uid]);
        $model = $query->one();
        if ($model) {
            $this->_model = $model;
        }
    }

    /**
     * 校验订单信息
     * @param string $attribute the attribute currently being validated
     */
    public function validateAttract($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $model = SpreadAttract::findByMobile($this->$attribute);
        if ($model) {
            $this->_model = $model;
        }
    }

    /**
     * 获取关联信息
     * @return SpreadAttract|null
     */
    public function getModel() {
        return $this->_model;
    }

    /**
     * 执行关联绑定
     * @inheritdoc
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('用户绑定失败');
        }
        //获取关联信息
        $spread = $this->getModel();
        if (!$spread) {
            return $this->dumpError('用户关系为空无推广操作！');
        }

        $branch = null;
        $member = Member::findAvailable([
            'user_id' => $spread->user_id
        ])->one();
        if ($member) {
            $branch = UserBranch::findOrNew(['user_id' => $this->user_id]);
            if ($branch->isNewRecord) {
                $branch->attributes = [
                    'member_id' => $member->id,
                    'member_user_id' => $member->user_id,
                    'status' => UserBranch::STATUS_ACTIVE,
                ];
            } else {
                $branch = null;
            }
        }

        Yii::error([
            'spread' => $spread->attributes,
            'member' => $member->attributes,
            'branch' => $branch->attributes,
        ]);

        $coupons = ShopCoupon::findByScope(ShopCoupon::SCOPE_SPREAD);
        //开启事务保存
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if ($branch) {
                if (!$branch->save()) {
                    throw new Exception($branch->getErrorMsg());
                }
                $branchLog = new MemberBranchLog();
                $branchLog->setTypeLog(MemberBranchLog::TYPE_BIND, $branch);
                if (!$branchLog->save()) {
                    throw new Exception($branchLog->getErrorMsg());
                }
            }
            if (!empty($coupons)) {
                foreach ($coupons as $coupon) {
                    $uc = UserCoupon::findOrNew([
                        'user_id' => $this->user_id,
                        'coupon_id' => $coupon->id,
                    ]);
                    if (!$uc->isNewRecord) {
                        continue;
                    }
                    if ($coupon->effective_time) {
                        $uc->expired_at = time() + $coupon->effective_time;
                    } elseif ($coupon->expired_at) {
                        $uc->expired_at = $coupon->expired_at;
                    }
                    if (!$uc->save()) {
                        throw new Exception($coupon->getErrorMsg());
                    }
                    $coupon->given++;
                    if (!$coupon->save()) {
                        throw new Exception($coupon->getErrorMsg());
                    }
                }
            }
            if (!$spread->delete()) {
                throw new Exception($spread->getErrorMsg());
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            return $this->dumpRetryError($e->getMessage());
        }
        return $this->dumpSuccess([
            'NewUserId' => $this->user_id,
            'Mobile' => $this->mobile,
            'Message' => '关系绑定成功！',
        ]);
    }

}
